package com.cms.controller.front;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.cms.Feedback;
import com.cms.entity.Member;
import com.cms.entity.Order;
import com.cms.entity.Payment;
import com.cms.routes.RouteMapping;
import com.cms.util.AlipayUtils;
import com.cms.util.ShopUtils;
import com.cms.util.SystemUtils;
import com.cms.util.WeixinUtils;


/**
 * Controller - 收款单
 * 
 * 
 * 
 */
@RouteMapping(url = "/payment")

public class PaymentController extends BaseController{

	/**
	 * 支付
	 */
	public void pay(){
		Payment.Method paymentMethod = getParaToEnum(Payment.Method.class,"paymentMethod");
		Payment.Type paymentType = getParaToEnum(Payment.Type.class,"paymentType");
		String sn = getPara("sn");
		BigDecimal amount = BigDecimal.ZERO;
		Payment payment = new Payment();
		payment.setCreateDate(new Date());
		payment.setModifyDate(new Date());
		payment.setMemberId(getCurrentMember().getId());
		payment.setType(paymentType.ordinal());
		if(Payment.Type.ORDER.ordinal()==paymentType.ordinal()){
			Order order = new Order().dao().findBySn(sn);
			amount = order.getAmount();
			payment.setOrderId(order.getId());
			payment.setInout("-");
		}else if(Payment.Type.RECHARGE.ordinal()==paymentType.ordinal()){
			amount = getParaToBigDecimal("amount");
			payment.setInout("+");
		}
		String out_trade_no = ShopUtils.getPaymentSn(sn);
		String paramsJson = JSONObject.toJSONString(new HashMap<>());
        payment.setAmount(amount);
        payment.setOutSn(out_trade_no);
        payment.setSn(sn);
        if(paymentMethod.name().startsWith(Payment.Method.ALIPAY.name())){
        	payment.setMethod(Payment.Method.ALIPAY.ordinal());
        }else if(paymentMethod.name().startsWith(Payment.Method.WEIXINPAY.name())){
        	payment.setMethod(Payment.Method.WEIXINPAY.ordinal());
        }else if(paymentMethod.ordinal()==Payment.Method.BALANCE.ordinal()){
			payment.setMethod(Payment.Method.BALANCE.ordinal());
		}
        payment.setStatus(Payment.Status.PENDING_PAYMENT.ordinal());
        payment.save();
        if(Payment.Method.ALIPAY_WEB.ordinal()==paymentMethod.ordinal()){
            AlipayUtils.webPay(out_trade_no,amount, "订单支付", SystemUtils.getConfig().getSiteUrl()+"/payment/alipayReturn/"+sn,paramsJson,getRequest(), getResponse());
            renderNull();
        }else if(Payment.Method.ALIPAY_WAP.ordinal()==paymentMethod.ordinal()){
            AlipayUtils.wapPay(out_trade_no,amount, "订单支付", SystemUtils.getConfig().getSiteUrl()+"/payment/alipayReturn/"+sn,paramsJson,getRequest(), getResponse());
            renderNull();
        }else if(Payment.Method.WEIXINPAY_WECHAT.ordinal()==paymentMethod.ordinal()){
            Map<String,String> result =WeixinUtils.wechatPay(out_trade_no,amount, "订单支付", getCurrentMember().getWeixinOpenId(),paramsJson, getRequest(), getResponse());
            for(String key : result.keySet()){
                setAttr(key, result.get(key));
            }
			setAttr("orderSn",sn);
            render("/templates/"+getTheme()+"/"+getDevice()+"/weixinpay_wechat.html");
        }else if(Payment.Method.WEIXINPAY_NATIVE.ordinal()==paymentMethod.ordinal()){
            Map<String,String> result =WeixinUtils.nativePay(out_trade_no,amount, "订单支付", paramsJson, getRequest(), getResponse());
            for(String key : result.keySet()){
                setAttr(key, result.get(key));
            }
            setAttr("codeUrl", result.get("code_url").toString());
			setAttr("orderSn",sn);
            render("/templates/"+getTheme()+"/"+getDevice()+"/weixinpay_native.html");
        }else if(Payment.Method.WEIXINPAY_H5.ordinal()==paymentMethod.ordinal()){
            Map<String,String> result =WeixinUtils.h5Pay(out_trade_no,amount, "订单支付", paramsJson, getRequest(), getResponse());
            setAttr("mwebUrl", result.get("mweb_url").toString());
			setAttr("orderSn",sn);
            render("/templates/"+getTheme()+"/"+getDevice()+"/weixinpay_h5.html");
        }else if(Payment.Method.BALANCE.ordinal()==paymentMethod.ordinal()){
        	Member member = new Member().dao().findById(getCurrentMember().getId());
        	BigDecimal newAmount = member.getAmount().subtract(payment.getAmount());
        	member.setAmount(newAmount);
        	member.update();
			new Order().paymentComplete(out_trade_no);
			redirect("/payment/balanceReturn/"+sn);
		}
	}


	/**
	 * 成功
	 */
	public void success(){
		Long orderId = getParaToLong("orderId");
		Order order = new Order().dao().findById(orderId);
		Member member = new Member().dao().findById(getCurrentMember().getId());
		setAttr("order",order);
		setAttr("member",member);
		render("/templates/"+getTheme()+"/"+getDevice()+"/payment_success.html");
	}
    
	
	/**
     * 支付宝同步
     */
	public void alipayReturn(){
		String sn = getPara(0);
		Order order = new Order().dao().findBySn(sn);
		redirect("/payment/success?orderId="+order.getId());
	}
	
   /**
     * 微信支付同步
     */
    public void weixinpayReturn(){
		String sn = getPara(0);
		Order order = new Order().dao().findBySn(sn);
		redirect("/payment/success?orderId="+order.getId());
    }

	/**
	 * 余额支付同步
	 */
	public void balanceReturn(){
		String sn = getPara(0);
		Order order = new Order().dao().findBySn(sn);
		redirect("/payment/success?orderId="+order.getId());
	}
	
	/**
     * 微信扫码支付检查
     */
	public void checkPay(){
	    Long orderId = getParaToLong("orderId");
	    Order order = new Order().dao().findById(orderId);
	    Map<String,Object> data = new HashMap<String, Object>();
	    if(Order.Status.PENDING_SHIPMENT.ordinal()==order.getStatus()){
	        data.put("isPayed", true);
	    }else{
	        data.put("isPayed", false);
	    }
	    renderJson(Feedback.success(data));
	}
}
